/* Copyright (C) 2015 Boren Zhang <bobo1993324@gmail.com>

   This file is part of Dekko email client for Ubuntu Devices/

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "CombinedFlattenContactFilterModel.h"
#include "CombinedFlattenContactModel.h"
#include "FlattenContactModel.h"
#include <QDebug>

namespace Dekko {
namespace Contacts {

CombinedFlattenContactFilterModel::CombinedFlattenContactFilterModel(QObject *parent)
	: QSortFilterProxyModel(parent) {
    m_emailSet = new QSet<QString>();
    setDynamicSortFilter(true);
}

CombinedFlattenContactFilterModel::~CombinedFlattenContactFilterModel()
{
    delete m_emailSet;
}

bool CombinedFlattenContactFilterModel::filterAcceptsRow(int source_row, const QModelIndex & source_parent) const {

    // every filter start with row = 0
    if (source_row == 0)
        m_emailSet->clear();

    QModelIndex sourceIndex = sourceModel()->index(source_row, 0);
    QString email = sourceIndex.data(FlattenContactModel::RoleEmail).toString();
    QString name = sourceIndex.data(FlattenContactModel::RoleName).toString();
//    qDebug() << __FILE__ << __func__ << "Filtering email: " << email;
    if (m_emailSet->contains(email)) {
        return false;
    }
    if (name.toLower().contains(filterRegExp().pattern().toLower())) {
        m_emailSet->insert(email);
        return true;
	}
    if (email.toLower().contains(filterRegExp().pattern().toLower())) {
        m_emailSet->insert(email);
		return true;
	}
    return false;
}

void CombinedFlattenContactFilterModel::setCombinedSourceModel(QAbstractItemModel *source)
{
    CombinedFlattenContactModel *model = static_cast<CombinedFlattenContactModel *>(source);
    Q_ASSERT(source);
    setSourceModel(model);
    emit modelsChanged();
}

}
}
